package com.example.projecttest;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpActivity extends AppCompatActivity implements View.OnClickListener {

    public static final String TAG="OkHttpActivity";
    public static final String HTTP_SELECT_URL="http://v3.wufazhuce.com:8000/api/hp/more/0";
    private Button btnGet;
    private TextView tv_result;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.okhttp_layout);
        initView();
    }

    private void initView() {
        btnGet = (Button) findViewById(R.id.btnGet);
        tv_result = (TextView) findViewById(R.id.tv_result);

        btnGet.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnGet:
                get();
                break;
        }
    }

    private void get(){
        OkHttpClient okHttpClient=new OkHttpClient();
        Request request=new Request.Builder().url(HTTP_SELECT_URL).build();
        Call call = okHttpClient.newCall(request);
        //同步请求
        //call.execute();
        //异步请求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, e.toString()+"==onResponse==");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response.isSuccessful()){
                    String result=response.body().string();
                    Log.d(TAG, result+"==onResponse==");
                }
            }
        });
    }
}
